#  Copyright 2009-2010 Michal Trzcinka
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#  http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software distributed
#  under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
#  CONDITIONS OF ANY KIND, either express or implied. See the License for the
#  specific language governing permissions and limitations under the License.

require 'digest/md5'

class User < ActiveRecord::Base

  @@account_types = %w{observer operator administrator}
  @@participant_account_types = %w{observer operator}

  belongs_to :workshop

  validates_presence_of :login, :hashed_password
  validates_uniqueness_of :login
  validates_inclusion_of :account_type, :in => @@account_types

  def self.account_types
    @@account_types
  end

  def self.participant_account_types
    @@participant_account_types
  end

  def self.authenticate(login, password)
    user = self.find_by_login(login)
    if user
      expected_password = encrypted_password(password)
      if user.hashed_password != expected_password
        user = nil
      end
    end
    user
  end

  def self.find_administrators
    self.find_all_by_account_type 'administrator'
  end

  def password
    @password
  end

  def password=(pwd)
    @password = pwd
    return if pwd.blank?
    self.hashed_password = User.encrypted_password(self.password)
  end

  def is_administrator
    self.account_type == 'administrator'
  end

  def is_participant
    self.account_type == 'operator' || self.account_type == 'observer'
  end

  def is_operator
    self.account_type == 'operator'
  end

  def can_edit_grid
    self.account_type == 'administrator' || self.account_type == 'operator'
  end

  private

  def self.encrypted_password(password)
    Digest::MD5.hexdigest(password)
  end

end
